package com.exam.scjp5.objectives.section_3;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ExampleSerializable2
{
    public static void main(String args[])
    {
        try
        {
            SerializableDog dog = new SerializableDog();
            dog.setName("Kit Kit");
            
            FileOutputStream fout = new FileOutputStream(new File("serializable2.dat"));
            ObjectOutputStream obout = new ObjectOutputStream(fout);
            obout.writeObject(dog);
            obout.close();
            fout.close();
            
            FileInputStream fin = new FileInputStream(new File("serializable2.dat"));
            ObjectInputStream obin = new ObjectInputStream(fin);
            dog = (SerializableDog)obin.readObject();
            obin.close();
            fin.close();
            
            System.out.println("Dog : " + dog.getName());
            
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

class SerializableDog implements Serializable
{
    private String name = null;
    
    public SerializableDog()
    {
        System.out.println("Dog()");
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }
    
    
    private void writeObject(ObjectOutputStream o)
    {
        try
        {
            System.out.println("writeObject");
            o.defaultWriteObject();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    private void readObject(ObjectInputStream o)
    {
        try
        {
            System.out.println("readObject");
            o.defaultReadObject();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}